import * as step from '@flow-step/step-toolkit'
import {SaeInterface} from './sae'
import {AbortChangeOrderRequest, AbortChangeOrderResponse} from '@alicloud/sae20190506'
import {IParams} from './params'

export async function rollback(params:IParams, sae: SaeInterface) {
    if (!params.CHANGE_ORDER_ID) {
        throw new Error('CHANGE_ORDER_ID is not set in environment variables');
    }
    step.info(`ROLLBACK DEPLOYMENT, changeOrderId: ${params.CHANGE_ORDER_ID} `)

    const request = new AbortChangeOrderRequest({
        changeOrderId: params.CHANGE_ORDER_ID,
    })
    let response: AbortChangeOrderResponse
    try {
        response = await sae.abortChangeOrder(request)
    }catch (error){
        throw new Error(`failed to abortChangeOrder: ${error}`)
    }

    if (response.body?.code != '200'){
        throw new Error(`rollback deployment failed, code: ${response.body?.code}, message: ${response.body?.message}`)
    }

    step.addOutput(`CHANGE_ORDER_ID=${params.CHANGE_ORDER_ID}`)
    step.addOutput(`APP_NAME=${params.APP_NAME}`)
    step.interaction.addLink(params.domestic?"发布单详情":"Change Order Details",`https://sae.console.aliyun.com/#/AppList/ChangeOrderDetail?appId=${params.APPLICATION_ID}&regionId=${params.regionID}&appName=${params.APP_NAME}&changeOrderId=${params.CHANGE_ORDER_ID}`,41)
    throw new Error(`CURRENT DEPLOYMENT IS CANCELLED MANUALLY`)

}